package com.zoshine.zzg.service;

import com.zoshine.zzg.dao.*;
import com.zoshine.zzg.exception.AppException;
import com.zoshine.zzg.exception.ErrorMessage;
import com.zoshine.zzg.pojo.*;
import com.zoshine.zzg.pojo.pojostatus.OrderStatus;
import com.zoshine.zzg.pojo.pojostatus.PrisonerSettlementStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 
 * @author 田沛凌
 * @time 2017年6月23日 下午3:33:53
 */
@Service
@Transactional
public class OrderPrisonerService extends BaseService<OrderPrisoner> {
	private  OrderPrisonerDao  orderPrisonerDao;
	private  OrderPrisonerDetailDao  orderPrisonerDetailDao;
	private  PrisonerInfoDao  prisonerInfoDao;
	private PrisonerAccountDao prisonerAccountDao;
	private  GoodsHistoryDetailDao goodsHistoryDetailDao;
	private PrisonerSettlementDao prisonerSettlementDao;
	@Autowired
	public void setOrderPrisonerDao(OrderPrisonerDao orderPrisonerDao) {
		this.orderPrisonerDao = orderPrisonerDao;
	}
	@Autowired
	public void setOrderPrisonerDetailDao(
			OrderPrisonerDetailDao orderPrisonerDetailDao) {
		this.orderPrisonerDetailDao = orderPrisonerDetailDao;
	}
	@Autowired
	public void setPrisonerInfoDao(PrisonerInfoDao prisonerInfoDao) {
		this.prisonerInfoDao = prisonerInfoDao;
	}

	@Autowired
	public void setPrisonerAccountDao(PrisonerAccountDao prisonerAccountDao) {
		this.prisonerAccountDao = prisonerAccountDao;
	}
	@Autowired
	public void setGoodsHistoryDetailDao(GoodsHistoryDetailDao goodsHistoryDetailDao) {
		this.goodsHistoryDetailDao = goodsHistoryDetailDao;
	}
	@Autowired
	public void setPrisonerSettlementDao(PrisonerSettlementDao prisonerSettlementDao) {
		this.prisonerSettlementDao = prisonerSettlementDao;
	}

	public void addOrderPrisoner(OrderPrisoner orderPrisoner) {
		//为空判断
//		if(null == orderPrisoner.getPrisonerInfo()){
//			throw new AppException(ErrorMessage.ACCOUNT_PRISONER_ID_CAN_NOT_NULL);
//		}
		//犯人账号
		PrisonerInfo prisonerInfo = prisonerInfoDao.selectByPrimaryKey(orderPrisoner.getPrisonerInfo());
		//犯人账户
		PrisonerAccount prisonerAccount = prisonerAccountDao.selectByPrimaryKey(prisonerInfo.getId());
		if(prisonerInfo == null){
			throw new AppException(ErrorMessage.PRISONER_MESSAGE_NOT_BE_NULL);
		}
		if(prisonerAccount == null){
			throw new AppException(ErrorMessage.PRISONER_MESSAGE_NOT_BE_NULL);
		}
		//新增点单
		OrderPrisoner orderTemp=new OrderPrisoner();
		orderTemp.setPrisonerInfo(orderPrisoner.getPrisonerInfo());
		orderTemp.setPrisonerName(prisonerInfo.getName());
		orderTemp.setArea(prisonerInfo.getArea());
		orderTemp.setSubArea(prisonerInfo.getSubArea());
		orderTemp.setId(baseIdWorker.createId());
		orderTemp.setTotalInvoice(0);
		orderTemp.setCreateTime(new Date());
		orderTemp.setUpdateTime(new Date());
		orderTemp.setCreateType(1);
		orderTemp.setStatus(OrderStatus.PENDINGAUDIR.getValue());
		//点单详情
		List<OrderPrisonerDetail> list =new ArrayList<>();
		OrderPrisonerDetail orderPrisonerDetail=null;
		if(null == orderPrisoner.getIdAndCounts() && orderPrisoner.getIdAndCounts().size() == 0){
			throw new AppException(ErrorMessage.GOODS_MESSAGE_NOT_BE_NULL);
		}
		Integer totalCount=0;
		Integer totalMoney=0;
		for (IdAndCount detail : orderPrisoner.getIdAndCounts()) {
			if( null == detail.getGoodsId()){
				throw new AppException(ErrorMessage.GOODS_ID_CAN_NOT_BE_NULL_OR_UNDER_ZERO);
			}
			if( null == detail.getGoodsCount() && detail.getGoodsCount() <= 0){
				throw new AppException(ErrorMessage.GOODS_COUNT_NOT_BE_NULL);
			}
			GoodsHistoryDetail goodsHistoryDetail = goodsHistoryDetailDao.selectByGoodsId(detail.getGoodsId());
			if(goodsHistoryDetail == null){
				throw new AppException(ErrorMessage.GOODS_MESSAGE_NOT_BE_NULL);
			}
			orderPrisonerDetail=new OrderPrisonerDetail();
			orderPrisonerDetail.setId(baseIdWorker.createId());
			orderPrisonerDetail.setOrderPrisonerId(orderTemp.getId());
			orderPrisonerDetail.setGoodsId(detail.getGoodsId());
			orderPrisonerDetail.setGoodsHistoryId(goodsHistoryDetail.getId());
			orderPrisonerDetail.setGoodsCount(detail.getGoodsCount());
			orderPrisonerDetail.setInvoiceCount(0);
			list.add(orderPrisonerDetail);
			totalCount=totalCount+detail.getGoodsCount();
			totalMoney=+totalMoney+detail.getGoodsCount()*goodsHistoryDetail.getGoodsSellPrice();
		}
		orderTemp.setTotalCount(totalCount);
		orderTemp.setTotalMoney(totalMoney);

		//限额判断
		//查询当月订单数及金额
		List<OrderPrisoner> orderPrisoners = orderPrisonerDao.selectByPrisonerId(orderPrisoner.getPrisonerInfo());
		//当月总金额
		Integer monthMoney = 0;
		for (OrderPrisoner op:orderPrisoners){
			monthMoney+=op.getTotalMoney();
		}
		//判断两种方式，本月剩余消费额度(E): 账户余额(Y)  冻结(D)  阀值(F)  当月下单(X)
		//E = (Y - D) > (F - X) ? (F - X) : (Y - D)
		Integer a = prisonerAccount.getBalance() - prisonerAccount.getFreezingAmount();
		Integer b = prisonerAccount.getConsumptionThreshold() - monthMoney;
		Integer c=a>b?b:a;
			if (c - totalMoney < 0 ){
				throw new AppException(ErrorMessage.MONEY_OUT_OF_RANGE);
			}else {
				prisonerAccount.setFreezingAmount(prisonerAccount.getFreezingAmount()+totalMoney);
			}

		//新增点单
		orderPrisonerDao.insert(orderTemp);
		//新增点单详情
		orderPrisonerDetailDao.batchInsert(list);
		//修改账户阈值
		prisonerAccountDao.update(prisonerAccount);
	}

	public List<OrderPrisonerDetail> pageOrderPrisonerDetailList(Long orderPrisonerId) {
		//为空判断
		if(orderPrisonerId == null){
			throw new AppException(ErrorMessage.ORDER_PRISONER_ID_CAN_NOT_NULL);
		}
		return orderPrisonerDetailDao.selectByOrderPrisonerId(orderPrisonerId);
	}

	public void delOrderPrisonerDetailList(String orderPrisonerDetailId) {
		 if (orderPrisonerDetailId == null || orderPrisonerDetailId.length()==0) {
	            throw new AppException(ErrorMessage.REQUEST_PARAM_CAN_NOT_NULL);
	        }
	        String[] pidArr = orderPrisonerDetailId.split(",");
	        List<Long> orderPrisonerDetailIdList = new ArrayList<>();
	        for (String pid : pidArr) {
	            try {
					orderPrisonerDetailIdList.add(Long.parseLong(pid));
	            } catch (NumberFormatException ex) {
	                throw new AppException(ErrorMessage.REQUEST_PARAM_TYPE_ERROR);
	            }
	        }
	        if (orderPrisonerDetailIdList.size() != 0) {
	        	orderPrisonerDetailDao.batchDelete(orderPrisonerDetailIdList);
	        }
	}
    public void editOrderPrisonerDetail(OrderPrisonerDetail orderPrisonerDetail) {
        if(null == orderPrisonerDetail.getId()){
            throw new AppException(ErrorMessage.ORDER_PRISONER_DETAIL_ID_CAN_NOT_NULL);
        }
        OrderPrisonerDetail temp = orderPrisonerDetailDao.selectByPrimaryKey(orderPrisonerDetail.getId());
        Integer before = temp.getGoodsCount();
        if(null == orderPrisonerDetail.getGoodsCount() && orderPrisonerDetail.getGoodsCount() <= 0){
            throw new AppException(ErrorMessage.GOODS_COUNT_NOT_BE_NULL);
        }
        Integer after = orderPrisonerDetail.getGoodsCount();
        /*商品数量的改变量*/
        Integer sum=after-before;
		GoodsHistoryDetail goodsHistoryDetail = goodsHistoryDetailDao.selectByGoodsId(temp.getGoodsId());
		if( goodsHistoryDetail == null){
            throw new AppException(ErrorMessage.GOODS_MESSAGE_NOT_BE_NULL);
        }
        Integer total=sum*goodsHistoryDetail.getGoodsSellPrice();
        /*修改详情*/
        temp.setGoodsCount(orderPrisonerDetail.getGoodsCount());
        orderPrisonerDetailDao.update(temp);
        /*修改点单数量及总额*/
        OrderPrisoner orderPrisoner = orderPrisonerDao.selectByPrimaryKey(temp.getOrderPrisonerId());
        orderPrisoner.setTotalCount(orderPrisoner.getTotalCount()+sum);
        orderPrisoner.setTotalMoney(orderPrisoner.getTotalMoney()+total);
        orderPrisonerDao.update(orderPrisoner);
    }
    public void editOrderPrisonerStatus(String idStr, Integer status) {
      //为空判断
		if (idStr == null || idStr.length()==0) {
			throw new AppException(ErrorMessage.REQUEST_PARAM_CAN_NOT_NULL);
		}

		String[] pidArr = idStr.split(",");
		List<Long> ids = new ArrayList<>();
		for (String id : pidArr) {
			OrderPrisoner orderPrisoner = orderPrisonerDao.selectByPrimaryKey(Long.parseLong(id));
			if(!orderPrisoner.getStatus().equals(OrderStatus.PENDINGAUDIR.getValue())){
				throw new AppException(ErrorMessage.AUDIT_STATUS_SHOLUD);
			}
			ids.add(Long.parseLong(id));
			//如果是审核失败，犯人账户阈值退回
			if (status.equals(OrderStatus.FAIL.getValue())){
				//审核失败，退回犯人点单余额
				PrisonerAccount prisonerAccount = prisonerAccountDao.selectByPrimaryKey(orderPrisoner.getPrisonerInfo());
				prisonerAccount.setConsumptionThreshold(prisonerAccount.getConsumptionThreshold()+orderPrisoner.getTotalMoney());
				prisonerAccountDao.update(prisonerAccount);
			}
		}

		orderPrisonerDao.batchUpdateStatus(status,ids);
    }

	/**
	 * 犯人结算
	 * @param idStr；
	 * @param status；
	 */
	public void settlement(String idStr, int status) {
		//为空判断
		if (idStr == null || idStr.length()==0) {
			throw new AppException(ErrorMessage.REQUEST_PARAM_CAN_NOT_NULL);
		}

		String[] pidArr = idStr.split(",");
		List<Long> ids = new ArrayList<>();
		for (String id : pidArr) {
			OrderPrisoner orderPrisoner = orderPrisonerDao.selectByPrimaryKey(Long.parseLong(id));
			if(!(orderPrisoner.getStatus().equals(OrderStatus.FINISHED.getValue()))){
				throw new AppException(ErrorMessage.GOODS_RETURN_SETTLEMENT);
			}
			ids.add(Long.parseLong(id));
			//生成犯人结算单,一条点单生成一条结算单
			PrisonerSettlement prisonerSettlement=new PrisonerSettlement();
			prisonerSettlement.setOrderPrisonerId(orderPrisoner.getId());
			//判断是否生成了结算单，如果没有则生成
			List<PrisonerSettlement> prisonerSettlements = prisonerSettlementDao.selectList(prisonerSettlement);
			if (prisonerSettlements.size() == 0){
				PrisonerInfo prisonerInfo = prisonerInfoDao.selectByPrimaryKey(orderPrisoner.getPrisonerInfo());
				prisonerSettlement.setId(baseIdWorker.createId());
				prisonerSettlement.setPrisonerAccount(orderPrisoner.getPrisonerInfo());
				prisonerSettlement.setPrisonsAccount(prisonerInfo.getOrgId());
				prisonerSettlement.setSettlementMoney(orderPrisoner.getTotalMoney());
				prisonerSettlement.setCreateTime(new Date());
				prisonerSettlement.setUpdateTime(new Date());
				prisonerSettlement.setStatus(PrisonerSettlementStatus.AUDITED.getValue());
				prisonerSettlementDao.insert(prisonerSettlement);
			}
		}
		orderPrisonerDao.batchUpdateStatus(status,ids);
	}

	/**
	 * 查询历史点单信息
	 * @param orderPrisoner 点单对象
	 * @return 点单信息集合
	 */
	public List<OrderPrisoner> orderPrisonerListHis(OrderPrisoner orderPrisoner){
		List<OrderPrisoner> orderPrisoners = orderPrisonerDao.selectListHis(orderPrisoner);
		return orderPrisoners;
	}

	/**
	 * 犯人收货页面(未完成数据)
	 * @param orderPrisoner 犯人点单信息
	 * @return 犯人未完成收货数据
	 */
    public List<OrderPrisoner> listFinish(OrderPrisoner orderPrisoner) {
    List<OrderPrisoner>	listFinish = orderPrisonerDao.selectListFinish(orderPrisoner);
    return listFinish;
    }
}
